package com.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.net.ClientException;
import com.net.RequestParameter;
/**
 * 
 * @author lenovo
 * 数据接口基类
 */
public abstract class BaseData
{
	/**
	 * 该函数为入口处调用函数，所有传递过来的参数都有该parameter提供
	 * @param parameter
	 */
	public abstract void startParse(final RequestParameter parameter) throws Exception, ClientException;
	
	//protected abstract void getConnection(final String urlS) throws IOException;
	
	//protected abstract void readStream(final String stream) throws IOException;
	
	/**
	 * 该函数的作用是解析出参数中所包含的参数值和数据
	 * @return 解析之后的参数utf-8字符串
	 * @throws UnsupportedEncodingException 
	 */
	protected  String encodeParameters(final RequestParameter parameter) throws Exception
	{
		
		if(parameter == null) 
		{
			return null;
		}
		
		StringBuffer sb = new StringBuffer();
		
		for(int loc = 0; loc < parameter.size(); loc++)
		{
			sb.append("&").append(URLEncoder.encode(parameter.getKey(loc), "UTF-8"))
			.append("=")
			.append(URLEncoder.encode(parameter.getValue(loc), "UTF-8"));
		} // for
		
		return sb.toString();
		
	} // encodeParameters
	
	protected String encodeParameters(final RequestParameter parameter, final String encode) throws Exception
	{
		if(encode.equals("utf-8"))
			return encodeParameters(parameter);
		
		if(parameter == null)
			return null;
		
		StringBuffer sb = new StringBuffer();
		for (int loc = 0; loc < parameter.size(); loc++ )
		{
			sb.append("&").append(URLEncoder.encode(parameter.getKey(loc), "gb2312"))
			.append("=")
			.append(URLEncoder.encode(parameter.getValue(loc), "gb2312"));
		}
		
		return sb.toString();
	}
	
	
	
	protected String getWebSource(final InputStream inputStream, final String encode) throws IOException
	{
		// 获取网页源代码
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encode);
		BufferedReader reader = new BufferedReader(inputStreamReader);
		
		StringBuffer buffer = new StringBuffer();
		String line = null;
		while ( ( line = reader.readLine() ) != null)
		{
			buffer.append(line + "\n");
		}
		reader.close();
		inputStreamReader.close();
		inputStream.close();
		
		return buffer.toString();
	}
	


	
}
